package com.zfast.config.mybatis;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.List;

/**
 * @author zgn
 * @Description: BaseService
 * @date 2022/5/12 0012
 */
@Transactional
public abstract class BaseService<PK extends Serializable, T>{
    @Autowired
    public BaseService(BaseMapper<T> baseMapper) {
        this.baseMapper = baseMapper;
    }
    Class<T> entityClass = (Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    protected BaseMapper<T> baseMapper;

    //region 1.数据库
    public int insert(T data) {
        int result = this.baseMapper.insert(data);
        return result;
    }

    public List<T> listAll() {
        return baseMapper.selectAll();
    }

    public List<T> list(T map) {
        return baseMapper.select(map);
    }

    public PageInfo<T> pageList(T map, Integer num, Integer size) {
        PageHelper.startPage(num, size);
        List<T> list = baseMapper.select(map);
        PageInfo<T> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    public T get(PK id){
        return this.baseMapper.selectByPrimaryKey(id);
    }

    public int delete(PK... ids){
        Example example = new Example(this.entityClass);
        example.createCriteria().andIn("id", Arrays.asList(ids));
        int result = this.baseMapper.deleteByExample(example);
        return result;
    }

    public int update(T... datas){
        int result = 0;
        T[] var3 = datas;
        int var4 = datas.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            T data = var3[var5];
            result += this.baseMapper.updateByPrimaryKeySelective(data);
        }
        return result;
    }
    //endregion
}
